<?php

/**
 * 订单模型管理
 * @author cjli
 *
 */
class OrderModel extends Model
{
    /**
     * 订单状态
     */
    const ORDER_UNCONFIRMED = 0; //未确认
    const ORDER_CONFIRMED = 1; //已确认
    const ORDER_COMPLETE = 2; //已完成
    const ORDER_CANCELED = -1; //取消
    const ORDER_DEL = -2; //已删除
    const ORDER_PAUSE = -3; //已暂停

    /**
     * 支付状态
     */
    const PAY_UNPAYED = 0;//未支付
    const PAY_PAYED = 1; //已支付
    const PAY_PARTIAL_REFUND = 2; //部分退款
    const PAY_FULL_REFUND = 3;//全部退款
    //const PAY_DINGJIN = 4;//已支付定金

    /**
     * 配送状态
     */
    const SHIPPING_UNSHIPPED = 0; //未发货
    const SHIPPING_SHIPPED = 1; //已发货
    const SHIPPING_RECEIVED = 2; //收货确认
    const SHIPPING_SHIPPED_PART = 3; //已发货(部分商品)
    const SHIPPING_RETURNED = 4; //退货

    /**
     * 定制类型
     */
    static $customType = array(
        '0' => '成衣',
        '1' => '初级定制',
        '2' => '高级定制',
    );

    static $orderStatus = array(
        self::ORDER_UNCONFIRMED => 'Unconfirmed',
        self::ORDER_CONFIRMED => 'Confirmed',
        self::ORDER_COMPLETE => 'Complete',
        self::ORDER_CANCELED => 'Cancel',
//    self::ORDER_DEL => 'Ordel Delete',
    );

    static $orderStatusCn = array(
        self::ORDER_UNCONFIRMED => '未确认',
        self::ORDER_CONFIRMED => '已确认',
        self::ORDER_COMPLETE => '已完成',
        self::ORDER_CANCELED => '取消',
        self::ORDER_DEL => '已删除',
        self::ORDER_PAUSE => '已暂停',
    );
    static $paymentStatus = array(
        self::PAY_UNPAYED => '未支付',
        self::PAY_PAYED => '已支付',
        self::PAY_PARTIAL_REFUND => '部分退款',
        self::PAY_FULL_REFUND => '全部退款',
        //self::PAY_DINGJIN => '已支付定金'
    );
    static $shippingStatus = array(
        self::SHIPPING_UNSHIPPED => '未发货',
        self::SHIPPING_SHIPPED => '已发货',
        self::SHIPPING_RECEIVED => '收货确认',
        self::SHIPPING_SHIPPED_PART => '已发货(部分商品)',
        self::SHIPPING_RETURNED => '退货'
    );
    static $giftshippingStatus = array(
        self::SHIPPING_UNSHIPPED => '未到货',
        self::SHIPPING_SHIPPED => '到货未领取',
        self::SHIPPING_RECEIVED => '已领取',
    );
    static $deliveryStatus = array(
        '1' => '正常',
        '2' => '已发货',
//  	'3' => '取消',
//  	'4' => '退货',
    );

    static $purchaseType = array(
        '1' => '退货',
        '2' => '换货',
        '3' => '维修',
        '4' => '退款',
    );

    static $purchaseStatus = array(
        '1' => '等待处理',
        '2' => '等待客户确认',
        '3' => '已解决',
        '4' => '取消'
    );


    /**
     * 根据订单ID获取订单日志列表
     * @param int $order_id 订单号
     * @return    array
     */
    public static function getOrdersLogList($order_id)
    {
        $order_log_db = D('orders_log');
        $logs = $order_log_db->where(array('order_id' => $order_id))->order('id DESC')->select();
        return $logs;
    }

    /**
     * 处理订单日志
     * @param Array $post 提交字段
     * @return boolean
     */
    public static function insertOrdersLog($post)
    {
        if (!isset($post['order_id']) || intval($post['order_id']) == 0) {
            return false;
        }
        $data = array(
            'order_id' => isset($post['order_id']) ? intval($post['order_id']) : 0,
            'order_status' => isset($post['order_status']) ? $post['order_status'] : 0,
            'payment_status' => isset($post['payment_status']) ? $post['payment_status'] : 0,
            'shipping_status' => isset($post['shipping_status']) ? $post['shipping_status'] : 0,
            'action_notice' => $post['action_notice'] ? trim($post['action_notice']) : null,
            'action_name' => $_SESSION['admin_user_info']['user_name'],
            'action_time' => time(),
        );

        $order_log_db = D('orders_log');
        $lastId = $order_log_db->add($data);
        return (boolean)$lastId;
    }

    /**
     * 获取订单关联产品列表
     * @param int $order_id 订单ID
     * @return array
     */
    public static function getOrderProductList($order_id)
    {
        $order_item_db = D('orders_items');
        $order_item_db->field('orders_items.*,product.small_img,product.cost_price,product.model_id,product.suppliers_id');
        $order_item_db->join('product ON product.id = orders_items.product_id');
        $order_item_db->where(array('order_id' => $order_id));
        $productList = $order_item_db->select();

        if ($productList) {
            foreach ($productList as &$product) {
                if ($product['attr']) {
                    $data = unserialize($product['attr']);
                    $card = (substr($data, 0, 6));
                    if ($card != 'Fabric') {
                        if ($data) {
                            $attributes = array();
                            if ($product['custom_type']) {
                                $attributes_pro = array();
                                foreach ($data as $vk => $val) {
                                    //获取定制选项中文名
                                    $where_attr = array('attribute_id' => $val["attr_id"],
                                        'language_id' => 6);
                                    $cn_attr_name = D('attribute_items')->where($where_attr)->getField('name');
                                    if ($val["attr_value_id"]) {
                                        //获取定制选项值在中文名
                                        $where_attr_val = array('att_value_id' => $val["attr_value_id"],
                                            'language_id' => 6);
                                        $cn_attr_value_name = D('attribute_values_items')->where($where_attr_val)->getField('attr_value');
                                    } else {
                                        $cn_attr_value_name = $val['attr_value'];
                                    }
                                    //解决more option里 订单商品定制数据显示不全的问题
                                    if(!isset($attributes[$val["attr_id"]])){
                                        $attributes[$val["attr_id"]] = $cn_attr_name . ':' . $cn_attr_value_name;
                                    }else{
                                        $attributes[$val["attr_id"]] .= ','.$cn_attr_value_name;
                                    }
                                    $attributes_pro[$val["attr_id"]] = $cn_attr_value_name;
                                }
                                //*******************
                                //解决绣字为空不需要显示绣字字体和颜色
                                $orderfigure = OrderModel::orderPrintFigure($product['id']);
                                list($font_1_key, $font_2_key, $font_zt_key, $font_color_key) = OrderModel::font_key($orderfigure, $product['model_id']);
                                $is_font = false;
                                $default_val = 99999;
                                if ($font_1_key != $default_val && !empty($attributes_pro[$font_1_key])) {
                                    $is_font = true;
                                } else {
                                    unset($attributes[$font_1_key]);
                                }
                                if ($font_2_key != $default_val && !empty($attributes_pro[$font_2_key])) {
                                    $is_font = true;
                                } else {
                                    unset($attributes[$font_2_key]);
                                }
                                if (!$is_font) {
                                    if ($font_zt_key != $default_val && isset($attributes[$font_zt_key]))
                                        unset($attributes[$font_zt_key]);
                                    if ($font_color_key != $default_val && isset($attributes[$font_color_key]))
                                        unset($attributes[$font_color_key]);
                                }
                                unset($attributes_pro);
                                //********************
                            } else {
                                foreach ($data as $vk => $val) {
                                    $attributes[] = $vk . ':' . $val;
                                }
                            }
                            $attribute = implode(' &nbsp;&nbsp;|&nbsp;&nbsp; ', $attributes);
                        }
                        $product['attr'] = $attribute;

                    }
                } else {
                    $product['attr'] = $card;
                }
                //获取订单中商品身形数据
                if ($product['measure_id']) {
                    $user_measure_db = D('user_measure');
                    $product['measure_data'] = $user_measure_db->find($product['measure_id']);

                    //*******************
                    //获取身型字段 兼容原先代码
                    if ($product['measure_data']) {
                        $measure_field = MeasureModel::user_measure_field();
                        foreach ($measure_field as $key => $val) {
                            $value = $product['measure_data'][$val['measure_field']];
                            if ($val['measure_field'] == 'age') {
                                $new_measure_data[$val['measure_field']] = $value;
                            } else if ($val['measure_field'] == 'chest_type') {
                                $new_measure_data['chest'][$val['field_type']] = $value;
                            } else if ($val['measure_field'] == 'stomach_type') {
                                $new_measure_data['stomach'][$val['field_type']] = $value;
                            } else {
                                $new_measure_data[$val['measure_field']][$val['field_type']] = $value;
                            }
                        }
                        $product['measure_data']['measure_data'] = $new_measure_data;
                    }
                    //********************

                }
            }
            unset($product);
        }
        return $productList;
    }

    //获取用户的商品类型
    public static function orderPrintFigure($order_item_id)
    {
        $order_item_db = D('orders_items');
        $productList = $order_item_db->where(array('id' => $order_item_id))->find();
        //dump($productList);exit;
        if ($productList) {          
            //获取商品的中文名称
            if ($productList['product_name']) {
                $where_name = array('product_id' => $productList['product_id'], 'language_id' => 6);
                $product_items = D('product_items')->where($where_name)->getField('name');
            }
            $buttonArr = array(); //纽扣数据
            //默认纽扣
            $product = ProductModel::getProductInfo($productList['product_id']);
            //礼服特殊处理
            if ( $product['model_id'] == 23 ){
              $cat_parentid = CategoryModel::get_category_parentid($product['catid']);
              if ( $product['catid'] == 2061 || $cat_parentid == 2061 ) {
                  $product['model_id'] = 18;
              } else {
                  $product['model_id'] = 2;
              }
            }
            if ( $product['model_id'] == 1 ) { //单西
                $buttonArr['24L'] = 3 + 8; //袖叉
                $buttonArr['32L'] = 1;
            } else if ( $product['model_id'] == 2 ) { //两件套
                $buttonArr['24L'] = 3 + 8; //袖叉
                $buttonArr['32L'] = 1;
            } else if ( $product['model_id'] == 14 ) { //衬衫
                $buttonArr['18L'] = 1;
                $buttonArr['14L'] = 1;
            } else if ( $product['model_id'] == 18 ) { //三件套
                $buttonArr['24L'] = 3 + 8; //袖叉
                $buttonArr['32L'] = 1;
            } else if ( $product['model_id'] == 20 ) { //马甲
                $buttonArr['24L'] = 1;
            } else if ( $product['model_id'] == 21 ) { //裤子
                $buttonArr['24L'] = 1;
            } else if ( $product['model_id'] == 22 ) { //大衣

            }

            if ($productList['attr']) {
                $data = unserialize($productList['attr']);
                if ($data) {
                    $attributes = array();
                    if ($productList['custom_type']) {
                        foreach ($data as $vk => $val) {
                            $attribute_values = D('attribute_values')->field('attr_img,attr_img2,button_type,button_qty')
                                                ->where(array('id'=>$val['attr_value_id']))->find();
                            //合计纽扣 （真假袖叉 已提出来单独处理了)
                            if ( $attribute_values['button_type'] && !in_array($val['attr_value_id'], array(136,342,210)) ) {
                                $button_type = $attribute_values['button_type'];
                                if( $buttonArr[$button_type] ) {
                                    $buttonArr[$button_type] += intval($attribute_values['button_qty']);  
                                }else{
                                    $buttonArr[$button_type] = intval($attribute_values['button_qty']);  
                                }
                            }
                            //衬衫门襟 TS001 TS002 TS003 为18L金属扣 数量4
                            if( in_array($val['attr_value_id'], array(827, 828, 829)) ) {
                                 $buttonArr['18Ljsk'] = 4;
                            }
                            //单西两件套三件套 如果有圆角袖叉,
                            if( in_array($val['attr_value_id'], array(762,765,761)) ) {
                                 $buttonArr['24L'] -= 8;
                            }

                            //获取定制选项中文名
                            $where_attr = array('attribute_id' => $val["attr_id"],
                                'language_id' => 6);
                            $cn_attr_name = D('attribute_items')->where($where_attr)->getField('name');
                            if (in_array($val["attr_id"], array(54, 70, 112, 134))) {
                                if ($val["attr_value_id"]) {
                                    //获取定制选项值在中文名
                                    $where_attr_val = array('att_value_id' => $val["attr_value_id"],
                                        'language_id' => 6);
                                    $cn_attr_value_name = D('attribute_values_items')->where($where_attr_val)->getField('attr_value');
                                } else {
                                    $cn_attr_value_name = $val['attr_value'];
                                }
                                $attributes[] = $val["attr_id"] . ':' . $cn_attr_value_name;
                                $attributes_more_array[$val["attr_value_id"]]['cn_attr_value_name'] = '有';
                            } else {
                                if ($val["attr_value_id"]) {
                                    //获取定制选项值在中文名
                                    $where_attr_val = array('att_value_id' => $val["attr_value_id"],
                                        'language_id' => 6);
                                    $cn_attr_value_name = D('attribute_values_items')->where($where_attr_val)->getField('attr_value');
                                } else {
                                    $cn_attr_value_name = $val['attr_value'];
                                }
                                $attributes[] = $val["attr_id"] . ':' . $cn_attr_value_name;
                                $attributes_array[$val["attr_id"]] = array('cn_name' => $cn_attr_name, 'cn_attr_value_name' => $cn_attr_value_name, 'attr_value_id' => $val["attr_value_id"], 'attr_img' =>$attribute_values['attr_img'], 'attr_img2' =>$attribute_values['attr_img2'] );
                            }
                        }

                    } else {
                        foreach ($data as $vk => $val) {
                            $attributes[] = $vk . ':' . $val;
                        }
                    }
                    $attribute = implode(' , ', $attributes);
                }
                $productList['attr'] = $attribute;
                $productList['attr_array'] = $attributes_array;
                $productList['attributes_more_array'] = $attributes_more_array;
                $productList['product_name'] = $product_items;
                $productList['buttonArr'] = $buttonArr;
            }

        }
        return $productList;
    }

    /**
     * 获取订单信息
     * @param int $order_id 订单ID
     * @return array
     */
    public static function getOrderInfo($order_id)
    {
        $order_db = D('orders');
        $orderInfo = $order_db->find($order_id);
        $language_id = C('language_id');
        $paymentInfo = PaymentModel::getPaymentItems($orderInfo['payment_method'], $language_id);
        $paymentInfo = reset($paymentInfo);
        $shippingInfo = ShippingModel::getShippingItems($orderInfo['shipping_id'], $language_id);
        $shippingInfo = reset($shippingInfo);
        $orderInfo['payment_method_name'] = $paymentInfo['title'];
        $orderInfo['shipping_method_name'] = $shippingInfo['title'];
        if ($orderInfo['data']) {
            $orderInfo['data'] = unserialize($orderInfo['data']);
        }
        return $orderInfo;
    }

    /**
     * 获取订单ID号
     * @param string $order_sn 订单号
     */
    public static function getOrderId($order_sn)
    {
        $order_db = D('orders');
        $order_id = $order_db->where(array('order_sn' => $order_sn))->getField('id');
        return $order_id ? $order_id : false;
    }

    /**
     * 更新订单
     * @param int $order_id 订单ID
     * @param array $post post数据
     * @return boolean
     */
    public static function update_order($order_id, $post)
    {
        $order_db = D('orders');
        $post['delivery_cid'] = intval($post['delivery_cid']);
        $post['delivery_pid'] = intval($post['delivery_pid']);

        $shipping_id = M('shipping')->field('id')->where("name='" . $_POST['shipping_method'] . "'")->find();

        $data = array(
            'order_status' => $post['order_status'],
            'payment_status' => $post['payment_status'],
            'shipping_status' => $post['shipping_status'],
            'shipping_id' => $shipping_id['id'],
            'payment_method' => $post['payment_method'],
            'shipping_method' => $post['shipping_method'],
            'shipping_no' => $post['shipping_no'] ? ($post['shipping_no']) : null,
            'data' => isset($post['data']) && $post['data'] ? serialize($post['data']) : null,
            'stockout' => intval($post['stockout']),
        );
        if ($post['shipping_status'] == 1 || $post['shipping_status'] == 2 || $post['shipping_status'] == 3 || $post['shipping_status'] == 4) {
            $data['shipping_time'] = time();
        }
        if ($post['delivery_first_name']) $data['delivery_first_name'] = $post['delivery_first_name'];
        if ($post['delivery_last_name']) $data['delivery_last_name'] = $post['delivery_last_name'];
        if ($post['delivery_phone']) $data['delivery_phone'] = $post['delivery_phone'];
        if ($post['delivery_mobile']) $data['delivery_mobile'] = $post['delivery_mobile'];
        if ($post['delivery_postcode']) $data['delivery_postcode'] = $post['delivery_postcode'];
        if ($post['delivery_cid']) $data['delivery_cid'] = $post['delivery_cid'];
        if ($post['delivery_pid']) $data['delivery_pid'] = $post['delivery_pid'];
        if ($post['delivery_province']) $data['delivery_province'] = $post['delivery_province'];
        if ($post['delivery_address']) $data['delivery_address'] = $post['delivery_address'];
        if ($post['delivery_address2']) $data['delivery_address2'] = $post['delivery_address2'];
        if ($post['delivery_address3']) $data['delivery_address3'] = $post['delivery_address3'];
        if ($post['delivery_time']) $data['delivery_time'] = $post['delivery_time'];

        //second delivery address
        if ($post['delivery2_first_name']) $data['delivery2_first_name'] = $post['delivery2_first_name'];
        if ($post['delivery2_last_name']) $data['delivery2_last_name'] = $post['delivery2_last_name'];
        if ($post['delivery2_phone']) $data['delivery2_phone'] = $post['delivery2_phone'];
        if ($post['delivery2_mobile']) $data['delivery2_mobile'] = $post['delivery2_mobile'];
        if ($post['delivery2_postcode']) $data['delivery2_postcode'] = $post['delivery2_postcode'];
        if ($post['delivery2_cid']) $data['delivery2_cid'] = $post['delivery2_cid'];
        if ($post['delivery2_province']) $data['delivery2_province'] = $post['delivery2_province'];
        if ($post['delivery2_address']) $data['delivery2_address'] = $post['delivery2_address'];
        if ($post['delivery2_address2']) $data['delivery2_address2'] = $post['delivery2_address2'];
        if ($post['delivery2_address3']) $data['delivery2_address3'] = $post['delivery2_address3'];


        if ($post['confirm_time']) {
            $data['confirm_time'] = $post['confirm_time'];
        }
        if ($post['payment_time']) {
            $data['payment_time'] = $post['payment_time'];
        }
        if ($post['product_amount']) {
            $data['product_amount'] = $post['product_amount'];
        }
        //更新国家
        if ($post['delivery_cid']) {
            $area_info = SiteModel::getRegionInfo($post['delivery_cid']);
            $data['delivery_country'] = $area_info['name'];
        }
        //更新省市
        if ($post['delivery_pid']) {
            $area_info = SiteModel::getRegionInfo($post['delivery_pid']);
            $data['delivery_province'] = $area_info['name'];
        }
        if ($post['end_time']) {
            $data['end_time'] = $post['end_time'];
        }

        foreach ($data as $key => $val) {
            if (is_null($val)) {
                unset($data[$key]);
            }
        }

        $result = $order_db->where(array('id' => $order_id))->save($data);
//  	echo $order_db->getLastSql();exit;
        self::updateOrderPrices($order_id);
        return (boolean)$result;
    }

    /**
     * 更新订单状态
     * @param int $order_id 订单ID
     * @param array $post post数据
     * @return boolean
     */
    public static function updateOrderStatus($order_id, $post)
    {
        $order_db = D('orders');
        $data = array();
        if (isset($post['order_status']))
            $data['order_status'] = intval($post['order_status']);
        if (isset($post['payment_status']))
            $data['payment_status'] = intval($post['payment_status']);
        if (isset($post['shipping_status']))
            $data['shipping_status'] = intval($post['shipping_status']);
        if ($data) {
            $order_db->where(array('id' => $order_id))->save($data);
        }
    }

    /**
     * 更新产品到订单产品关联表
     * @param int $oiid 订单关联表ID
     * @param int $product_id 产品ID
     * @param float $pay_price 支付价格
     * @param int $qty 数量
     * @return boolean
     */
    public static function updateOrderItems($oiid, $pay_price, $qty)
    {
        $order_items_db = D('orders_items');
        $info = $order_items_db->find($oiid);
        if (!$info) {
            return false;
        }
        $qty = intval($qty) > 0 ? intval($qty) : 1;
        $pay_price = floatval($pay_price);

        $data = array(
            'qty' => $qty,
            'pay_price' => $pay_price,
            'total_weight' => $qty * $info['weight'],
            'total_amount' => $qty * $pay_price,
        );
        $order_items_db->where('id=' . $oiid)->save($data);

        //更新产品库存
        if ($qty != $info['qty']) {
            ProductModel::updateStock($info['product_id'], ($qty - $info['qty']));
        }
    }

    /**
     * 添加产品到订单产品关联表
     * @param int $order_id 订单ID号
     * @param array $post post数据
     * @return boolean
     */
    public static function insertOrderItems($order_id, $post)
    {
        $order_items_db = D('orders_items');
        $pay_price = isset($post['pay_price']) ? floatval($post['pay_price']) : $post['sell_price'];
        $data = array(
            'order_id' => $order_id,
            'product_id' => $post['product_id'],
            'product_sn' => $post['product_sn'],
            'product_name' => $post['product_name'],
            'sell_price' => $post['sell_price'],
            'qty' => $post['qty'],
            'weight' => $post['weight'],
            'total_weight' => $post['qty'] * $post['weight'],
            'pay_price' => $pay_price,
            'total_amount' => $pay_price * $post['qty'],
            'attr' => (isset($post['attr']) && $post['attr']) ? serialize($post['attr']) : null,
        );
        $lastId = $order_items_db->add($data);
        if ($lastId) {
            //更新产品库存
            ProductModel::updateStock($post['product_id'], (-1) * $post['qty']);
        }
        return (boolean)$lastId;
    }


    /**
     * 更新订单价格
     * @param int $order_id 订单ID号
     * @return vod
     */
    public static function updateOrderPrices($order_id)
    {
        $orderInfo = self::getOrderInfo($order_id);
        //dump($orderInfo);exit;
        if (!$orderInfo) return false;

        $order_items_db = D('orders_items');

        //获取产品总价格
        $product_amount = 0;
        $total_weight = 0;
        $total_number = 0;
        $productList = $order_items_db->field('total_weight,total_amount,qty')->where('order_id=' . $order_id)->select();
        if ($productList) {
            foreach ($productList as $product) {
                $product_amount += $product['total_amount'];
                $total_weight += $product['total_weight'];
                $total_number += $product['qty'];
            }
        }

        //获取配送费用
        $shipping_fee = ShippingModel::getShippingFee($orderInfo['shipping_method'], $orderInfo['delivery_cid'], $product_amount, $total_weight, $total_number);

        //获取支付费用
        //$payment_fee = PaymentModel::getPaymeentFee($orderInfo['payment_method'], $product_amount);
        $payment_fee = $orderInfo['payment_fee'];
        //总价格 = 产品价格+支付费用+配送费用
        $order_amount = floatval(floatval($product_amount) + floatval($payment_fee) + floatval($shipping_fee));
        //已付费用 = 余额支付+积分支付+优惠金额
        $paid_amount = floatval(floatval($orderInfo['surplus_money']) + floatval($orderInfo['integral_money']) + floatval($orderInfo['discount_amount']));
        //已付费用 + 红包 + 优惠全券
        $paid_amount += floatval(floatval($orderInfo['hongbao_money']) + floatval($orderInfo['coupon_money']));

        //支付费用
        $pay_amount = $total_amount = floatval($order_amount - $paid_amount);

        if ($paid_amount) {
            //订单应付费用
            $data = array(
                'product_amount' => $product_amount,
                'payment_fee' => $payment_fee,
                'shipping_fee' => $shipping_fee,
                'order_amount' => $order_amount,
                'pay_amount' => $pay_amount,
                //  		'payment_status' => $payment_status,
            );
            if (isset($payment_status)) {
                $data['payment_status'] = $payment_status;
            }
            if (isset($order_status)) {
                $data['order_status'] = $order_status;
            }
            if (isset($surplus_money) && $surplus_money) {
                $data['surplus_money'] = $surplus_money;
            }
            $order_db = D('orders');
            $order_db->where('id=' . $order_id)->save($data);
        } else {

            if ($total_amount == 0) {
                $pay_amount = 0;
                if ($orderInfo['order_status'] == self::ORDER_CANCELED || $orderInfo['order_status'] == self::ORDER_DEL || $orderInfo['order_status'] == self::ORDER_PAUSE) {
                    //$payment_status = self::PAY_UNPAYED;
                } else {
                    $order_status = self::ORDER_CONFIRMED;
                    $payment_status = self::PAY_PAYED;
                }

            } //支付的费用多于订单费用要退款
            elseif ($total_amount < 0) {
                $pay_amount = 0;
                $surplus_money = floatval(floatval($orderInfo['surplus_money']) + $total_amount);
                $payment_status = self::PAY_PAYED;
                $order_status = self::ORDER_CONFIRMED;
//  		$payment_status = self::PAY_PARTIAL_REFUND;
                //退款
                if ($orderInfo['user_id']) {
                    UserModel::logAccountChange($orderInfo['user_id'], $total_amount, 0, 0, 0, L('_ORDER_REFUND_') . ' ' . L('order number : ') . $orderInfo['order_sn'], UserModel::ACT_REFUND);
                }

                //退款记录
                $data = array(
                    'user_id' => $orderInfo['user_id'] ? $orderInfo['user_id'] : 0,
                    'user_name' => $orderInfo['delivery_first_name'] . ' ' . $orderInfo['delivery_last_name'],
                    'order_id' => $orderInfo['id'],
                    'order_sn' => $orderInfo['order_sn'],
                    'return_amount' => $total_amount,
                    'return_points' => 0,
                    'return_rank_points' => 0,
                    'admin_user' => '',
                    'admin_note' => '订单退款，订单号：' . $orderInfo['order_sn'] . PHP_EOL . '支付方式：' . $orderInfo['payment_method_name'],
                    'status' => 0,
                );
                if ($orderInfo['user_id']) {
                    //$data['admin_note'] .='<br/>已经退入余额.';
                    //$data['status'] = 2;
                    $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
                    $data['user_name'] = $userInfo['username'] ? $userInfo['username'] : '会员不存在';
                } else {
                    $data['user_name'] = 'Anonymous';
                }
                self::updatePayReturnLog($data);
            }

            //订单应付费用
            $data = array(
                'product_amount' => $product_amount,
                'payment_fee' => $payment_fee,
                'shipping_fee' => $shipping_fee,
                'order_amount' => $order_amount,
                'pay_amount' => $pay_amount,
//  		'payment_status' => $payment_status,
            );

            if (isset($payment_status)) {
                $data['payment_status'] = $payment_status;
            }
            if (isset($order_status)) {
                $data['order_status'] = $order_status;
            }
            if (isset($surplus_money) && $surplus_money) {
                $data['surplus_money'] = $surplus_money;
            }
            //dump($data);exit;
            $order_db = D('orders');
            $order_db->where('id=' . $order_id)->save($data);
            //echo $order_db->getLastSql();exit;
        }
    }

    /**
     * 订单配货产品信息列表
     * @param int $order_id 订单号
     * @param int $ordery_delivery_id 发货单ID号
     */
    public static function getOrderDeliveryProductList($order_id, $ordery_delivery_id = 0)
    {
        $orderProductList = self::getOrderProductList($order_id);
        if ($orderProductList) {
            foreach ($orderProductList as $key => $item) {
                $orderProductList[$key]['send_number'] = self::getDeliverySendNumber($item['id'], $ordery_delivery_id, 'all');
                $orderProductList[$key]['stock'] = ProductModel::getProductStock($item['product_id']);
            }
        }
        return $orderProductList;
    }

    /**
     * 统计发货单数量
     * @param int $order_id 订单号
     */
    public static function getDeliveryCount($order_id)
    {
        $order_delivery_db = D('orders_delivery');
        $count = $order_delivery_db->where(array('order_id' => $order_id))->count();
        return (boolean)$count;
    }

    /**
     * 判断是否须要配货
     * @param int $order_id 订单号
     */
    public static function getHavingDelivery($order_id)
    {
        $orderProductList = self::getOrderProductList($order_id);
        if ($orderProductList) {
            foreach ($orderProductList as $key => $item) {
                $send_number = self::getDeliverySendNumber($item['id'], null, 'all');
                if ($send_number != $item['qty']) {
                    return true;
                    break;
                }
            }
        }
        return false;
    }

    /**
     * 得到新发货单号
     * @return  string
     */
    public static function getDeliverySn()
    {
        /* 选择一个随机的方案 */
        mt_srand((double)microtime() * 1000000);

        return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 更新发货单状态
     * @param int $order_id 订单ID
     */
    public static function updateDeliveryStatus($order_id)
    {
        $status = 0;
        $order_items_db = D('orders_items');
        $order_delivery_product_db = D('orders_delivery_product');
        $itemsList = $order_items_db->field('id,qty')->where('order_id=' . $order_id)->select();
        foreach ($itemsList as $item) {
            //已经发了的货
            $send_number = self::getDeliverySendNumber($item['id']);
            if ($send_number) {
                //部分发
                if ($item['qty'] > $send_number) {
                    $status = 1;
                    break;
                } //存在未发货的产品
                elseif ($status == -1) {
                    $status = 1;
                    break;
                } else { //全发
                    $status = 2;
                }
            } elseif ($send_number == 0) { //存在未发货的产品
                if ($status == 2)
                    $status = 1;
                else
                    $status = -1;
            }
        }

        if ($status == 1) {
            $status_data = array('shipping_status' => self::SHIPPING_SHIPPED_PART);
        } elseif ($status == 2) {
            $status_data = array(
                'shipping_status' => self::SHIPPING_SHIPPED,
            );
        }
        if (isset($status_data) && $status_data) {
            self::updateOrderStatus($order_id, $status_data);
        }
    }

    /**
     * 获取每个商品的已发货总数
     * @param int $order_items_id 订单商品详细ID
     * @param int $ordery_delivery_id 发货单ID
     * @param int $status 配送状态
     */
    public static function getDeliverySendNumber($order_items_id, $ordery_delivery_id = 0, $status = 2)
    {
        $order_delivery_product_db = D('orders_delivery_product');
        $where['orders_items_id'] = $order_items_id;
        if ($ordery_delivery_id) {
            $where['orders_delivery_id'] = $ordery_delivery_id;
        } else {
            if (is_numeric($status)) {
                $where['orders_delivery.status'] = $status; //已发
            }
        }
        $order_delivery_product_db->join('orders_delivery ON orders_delivery.id=orders_delivery_product.orders_delivery_id');
        $order_delivery_product_db->where($where);
        $send_number = $order_delivery_product_db->getField('SUM(send_number) AS count');
        return intval($send_number);
    }

    /**
     * 获取物流单号
     * @param int $order_id 订单ID
     */
    public static function getShippingNumber($order_id)
    {
        $shippingNoArray = null;
        $orders_delivery_db = D('orders_delivery');
        $shippingnumbers = $orders_delivery_db->field('shipping_no')->where('order_id=' . $order_id)->select();
        if ($shippingnumbers) {
            foreach ($shippingnumbers as $no) {
                $shippingNoArray[] = $no['shipping_no'];
            }
        }
        return $shippingNoArray ? join(',', $shippingNoArray) : null;
    }

    /**
     * 获取发货单详细信息
     * @param int $delivery_id 发货单ID
     */
    public static function getDeliveryInfo($delivery_id)
    {
        $orders_delivery_db = D('orders_delivery');
        $deliveryInfo = $orders_delivery_db->where('id=' . $delivery_id)->find();
        return $deliveryInfo;
    }

    /**
     * 获取发货单商品列表
     * @param int $order_id 订单ID号
     * @param int $delivery_id 发货单ID
     */
    public static function getDeliveryProductList($order_id, $delivery_id)
    {
        //发货商品
        $order_item_db = D('orders_items');
        $order_item_db->field('orders_items.*,product.small_img,product.stock, odp.send_number,od.delivery_sn,od.shipping_no,od.update_time');
        $order_item_db->join('product ON product.id = orders_items.product_id');
        $order_item_db->join('orders_delivery_product AS odp ON odp.orders_items_id=orders_items.id');
        $order_item_db->join('orders_delivery AS od ON od.id = odp.orders_delivery_id');
        $order_item_db->where(array('orders_items.order_id' => $order_id, 'od.id' => $delivery_id));
        $productList = $order_item_db->select();
        if ($productList) {
            foreach ($productList as &$product) {
                if ($product['attr']) {
                    $data = unserialize($product['attr']);
                    if ($data) {
                        $attributes = array();
                        if ($product['custom_type']) {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $val['attr_name'] . ':' . $val['attr_value'];
                            }
                        } else {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $vk . ':' . $val;
                            }
                        }
                        $attribute = implode(' , ', $attributes);
                    }
                    $product['attr'] = $attribute;
                }
            }
            unset($product);
        }
        return $productList;
    }

    /**
     * 赠送全额订单积分
     * @param int $order_id 订单号
     */
    public static function sendOrderPoints($order_id)
    {
        $orderInfo = self::getOrderInfo($order_id);
        if (!$orderInfo || $orderInfo['user_id'] == 0) {
            return false;
        }
        $orders_items_db = D('orders_items');
        $orders_items_db->field('orders_items.qty,product.sell_price,product.rank_integral,product.integral');
        $orders_items_db->join('product ON product.id=orders_items.product_id');
        $orders_items_db->where(array('orders_items.order_id' => $order_id));
        $itemsList = $orders_items_db->select();
        if ($itemsList) {
            $total_rank_integral = 0;
            $total_integral = 0;
            foreach ($itemsList as $item) {
                $rank_integral = $item['rank_integral'] == -1 ? $item['sell_price'] : intval($item['rank_integral']);
                $integral = $item['integral'] == -1 ? $item['sell_price'] : intval($item['integral']);
                $total_rank_integral += $item['qty'] * $rank_integral;
                $total_integral += $item['qty'] * $integral;
            }
            UserModel::logAccountChange($orderInfo['user_id'], 0, 0, $total_rank_integral, $total_integral, L('Successful payment') . ' ' . L('order number : ') . $orderInfo['order_sn'], UserModel::ACT_PAY);
        }
    }

    /**
     * 全额退订单积分并退款
     * @param int $order_id 订单号
     */
    public static function returnedOrderALLPoints($order_id)
    {
        $orderInfo = self::getOrderInfo($order_id);
        if (!$orderInfo) {
            return false;
        }
        $orders_items_db = D('orders_items');
        $orders_items_db->field('orders_items.qty,orders_items.product_id,product.sell_price,product.rank_integral,product.integral');
        $orders_items_db->join('product ON product.id=orders_items.product_id');
        $orders_items_db->where(array('orders_items.order_id' => $order_id));
        $itemsList = $orders_items_db->select();
        if ($itemsList) {
            $total_rank_integral = 0;
            $total_integral = 0;
            foreach ($itemsList as $item) {
                $rank_integral = $item['rank_integral'] == -1 ? $item['sell_price'] : intval($item['rank_integral']);
                $integral = $item['integral'] == -1 ? $item['sell_price'] : intval($item['integral']);
                $total_rank_integral += $item['qty'] * $rank_integral;
                $total_integral += $item['qty'] * $integral;
                //退库存
                ProductModel::updateStock($item['product_id'], (-1) * $item['qty']);
            }
            /***********TODO改变手动退*********/
            //退款退积分
            //UserModel::logAccountChange($orderInfo['user_id'], $orderInfo['pay_amount'], 0, (-1)*$total_rank_integral, (-1)*$total_integral, L('_ORDER_REFUND_').' '.L('order number : ').$orderInfo['order_sn'], UserModel::ACT_REFUND);
            //退款记录
            $data = array(
                'user_id' => $orderInfo['user_id'] ? $orderInfo['user_id'] : 0,
                'order_id' => $orderInfo['id'],
                'order_sn' => $orderInfo['order_sn'],
                'return_amount' => $orderInfo['pay_amount'],
                'return_points' => $total_integral,
                'return_rank_points' => $total_rank_integral,
                'admin_user' => '',
                'admin_note' => '订单退款，订单号：' . $orderInfo['order_sn'] . '; ' . PHP_EOL . '支付方式：' . $orderInfo['payment_method_name'],
                'status' => 0,
            );
            if ($orderInfo['user_id']) {
                //$data['admin_note'] .=' 已经退入余额.';
                //$data['status'] = 2;
                $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
                $data['user_name'] = $userInfo['username'] ? $userInfo['username'] : '会员不存在';
            } else {
                $data['user_name'] = 'Anonymous';
            }
            /**
             * //退款邮件
             * if($orderInfo['delivery_email']){
             * $email_template = UserModel::getEmailTemplateInfo('payReturnEmail', $orderInfo['language_id']);
             * //发邮件
             * if($email_template){
             * $mailInstance = D(WEB_APP_NAME.'://Email');
             * $content = str_replace('{$user_name}', $orderInfo['delivery_first_name'].' '.$orderInfo['delivery_last_name'], $email_template['content']);
             * $content = str_replace('{$admin_note}', $data['admin_note'], $content);
             * $content = str_replace('{$order_sn}', $orderInfo['order_sn'], $content);
             * $title = str_replace('{$order_sn}', $orderInfo['order_sn'], $email_template['title']);
             * $content = $mailInstance->replaceMail($content);
             * $title = $mailInstance->replaceMail($title);
             * $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
             * }
             * }
             **/
            self::updatePayReturnLog($data);
        }
    }

    /**
     * 订单部分退积分退款
     * @param int $order_id 订单号
     */
    public static function returnedPartOrderPoints($order_id)
    {
        $orderInfo = self::getOrderInfo($order_id);
        if (!$orderInfo) {
            return false;
        }
        //如果没有发过货全退
        $orders_delivery_db = D('orders_delivery');
        $count = $orders_delivery_db->where(array('order_id' => $order_id, 'status' => 2))->count();
        if (!$count) {
            self::returnedOrderALLPoints($order_id);
            return true;
        }

        $orders_items_db = D('orders_items');
        $orders_items_db->field('orders_items.id,orders_items.qty,orders_items.product_id,orders_items.pay_price,product.sell_price,product.rank_integral,product.integral');
        $orders_items_db->join('product ON product.id=orders_items.product_id');
        $orders_items_db->where(array('orders_items.order_id' => $order_id));
        $itemsList = $orders_items_db->select();
        if ($itemsList) {
            $total_rank_integral = 0;
            $total_integral = 0;
            $total_amount = 0;
            foreach ($itemsList as $item) {
                $send_number = self::getDeliverySendNumber($item['id']);
                if ($item['qty'] == $send_number) continue;
                $qty = $item['qty'] = $send_number;

                $rank_integral = $item['rank_integral'] == -1 ? $item['sell_price'] : intval($item['rank_integral']);
                $integral = $item['integral'] == -1 ? $item['sell_price'] : intval($item['integral']);
                $total_rank_integral += $qty * $rank_integral;
                $total_integral += $qty * $integral;
                $total_amount += $qty * $item['pay_price'];
                //退库存
                ProductModel::updateStock($item['product_id'], (-1) * $qty);
            }
            //退款退积分
            //UserModel::logAccountChange($orderInfo['user_id'],$total_amount, null, (-1)*$total_rank_integral, (-1)*$total_integral, L('_ORDER_REFUND_').' '.L('order number : ').$orderInfo['order_sn'], UserModel::ACT_REFUND);

            //退款记录
            $data = array(
                'user_id' => $orderInfo['user_id'] ? $orderInfo['user_id'] : 0,
                'order_id' => $orderInfo['id'],
                'order_sn' => $orderInfo['order_sn'],
                'return_amount' => $total_amount,
                'return_points' => $total_integral,
                'return_rank_points' => $total_rank_integral,
                'admin_user' => 'system',
                'admin_note' => '订单退款，订单号：' . $orderInfo['order_sn'] . PHP_EOL . '支付方式：' . $orderInfo['payment_method_name'],
                'status' => 0,
            );
            if ($orderInfo['user_id']) {
                //$data['admin_note'] .='<br/>已经退入余额';
                //$data['status'] = 2;
                $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
                $data['user_name'] = $userInfo['username'] ? $userInfo['username'] : '会员不存在';
            } else {
                $data['user_name'] = 'Anonymous';
            }
            /**
             * //退款邮件
             * if($orderInfo['delivery_email'] && $total_amount>0 && $total_amount>'0.00'){
             * $email_template = UserModel::getEmailTemplateInfo('payReturnEmail', $orderInfo['language_id']);
             * //发邮件
             * if($email_template){
             * $mailInstance = D(WEB_APP_NAME.'://Email');
             * $content = str_replace('{$user_name}', $orderInfo['delivery_first_name'].' '.$orderInfo['delivery_last_name'], $email_template['content']);
             * $content = str_replace('{$admin_note}', $data['admin_note'], $content);
             * $content = str_replace('{$order_sn}', $orderInfo['order_sn'], $content);
             * $title = str_replace('{$order_sn}', $orderInfo['order_sn'], $email_template['title']);
             * $content = $mailInstance->replaceMail($content);
             * $title = $mailInstance->replaceMail($title);
             * $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
             * }
             * }
             */
            self::updatePayReturnLog($data);

        }
        //发放分成
        self::sendOrderSharing($order_id);
    }

    /**
     * 订单取消退回支付使用的积分和余额
     * @param int $order_id 订单ID
     */
    public static function returnedOrderSurplusANDPoints($order_id)
    {
        $order_db = D('orders');
        $orderInfo = $order_db->field('user_id,id,surplus_money,integral,order_sn')->find($order_id);
        if ($orderInfo['user_id']) {
            UserModel::logAccountChange($orderInfo['user_id'], $orderInfo['surplus_money'], 0, 0, $orderInfo['integral'], L('The order cancal') . ' ' . L('order number : ') . $orderInfo['order_sn'], UserModel::ACT_REFUND);
        }
        $data = array(
            'surplus_money' => 0,
            'integral' => 0,
            'integral_money' => 0,
            'payment_status' => self::PAY_UNPAYED,
        );
        $order_db->where(array('id' => $order_id))->save($data);
    }

    /**
     * 更新退款记录
     * @param array $post post数组
     * @param int $pid 记录ID
     */
    public static function updatePayReturnLog($post, $pid = null)
    {
        return false;
        $pay_return_db = D('orders_pay_return');
        $return_amount = floatval($post['return_amount']);
        if ($post['return_amount'] == 0 || $post['return_amount'] == '0.00') {
            return false;
        }
        $data = array(
            'return_amount' => $return_amount,
            'return_points' => $post['return_points'],
            'return_rank_points' => $post['return_rank_points'],
            'admin_note' => trim($post['admin_note']),
            'admin_user' => $post['admin_user'] ? $post['admin_user'] : 'system',
            'end_time' => time(),
            'status' => intval($post['status']),
        );

        if (!$pid) {
            $data['user_id'] = $post['user_id'] ? $post['user_id'] : null;
            $data['user_name'] = $post['user_name'] ? $post['user_name'] : null;
            $data['order_id'] = $post['order_id'] ? $post['order_id'] : null;
            $data['order_sn'] = $post['order_sn'] ? $post['order_sn'] : null;
            $data['add_time'] = time();
            $pid = $pay_return_db->add($data);
        } else {
            $pay_return_db->where('id=' . $pid)->save($data);

            if ($post['status'] == 2) {
                $pay_return_db = D('orders_pay_return');
                $payInfo = $pay_return_db->find($pid);

                $orders_db = D('orders');
                $data2['order_status'] = -1;
                $orders_db->where('order_sn="' . $payInfo['order_sn'] . '"')->save($data2);
            }
        }
        return $pid;
    }

    /**
     * 更新退款记录 新方式
     * @param array $post post数组
     * @param int $pid 记录ID
     */
    public static function updatePayReturnLogNew($post, $pid = null)
    {
        $pay_return_db = D('orders_pay_return');
        $return_amount = floatval($post['return_amount']);

        $data = array(
            'return_amount' => isset($post['return_amount']) ? $post['return_amount'] : 0,
            'return_points' => isset($post['return_points']) ? $post['return_points'] : 0,
            'return_rank_points' => isset($post['return_rank_points']) ? $post['return_rank_points'] : 0,
            'admin_note' => isset($post['admin_note']) ? trim($post['admin_note']) : NULL,
            'admin_user' => isset($post['admin_user']) ? trim($post['admin_user']) : NULL,
            'status' => isset($post['status']) ? intval($post['status']) : NULL,
            'user_id' => isset($post['user_id']) ? intval($post['user_id']) : NULL,
            'user_name' => isset($post['user_name']) ? trim($post['user_name']) : NULL,
            'order_id' => isset($post['order_id']) ? intval($post['order_id']) : NULL,
            'order_sn' => isset($post['order_sn']) ? trim($post['order_sn']) : NULL,
            'check_user' => isset($post['check_user']) ? trim($post['check_user']) : NULL,
            'refuse_note' => isset($post['refuse_note']) ? trim($post['refuse_note']) : NULL,
            'apply_amount' => isset($post['apply_amount']) ? trim($post['apply_amount']) : NULL,
            'apply_type' => isset($post['apply_type']) ? trim($post['apply_type']) : NULL,
        );
        foreach ($data as $key => $val) {
            if (is_null($val)) {
                unset($data[$key]);
            }
        }
        // var_dump($data);exit;
        if (!$pid) {
            $data['add_time'] = time();
            $pid = $pay_return_db->add($data);

            //退款记录之操作人记录
            $pay_return_log = array(
                'paytid' => $pid,
                'payt_status' => $data['status'],
                'action_name' => $data['admin_user'],
                'action_time' => $data['add_time'],
            );
        } else {
            $data['end_time'] = time();
            $pay_return_db->where('id=' . $pid)->save($data);

            //退款记录之操作人记录
            $pay_return_log = array(
                'paytid' => $pid,
                'payt_status' => $data['status'],
                'action_name' => $data['check_user'],
                'action_time' => $data['end_time'],
            );

            //不改变订单状态
            // if($post['status'] == 2){
            //   $pay_return_db = D('orders_pay_return');
            //   $payInfo = $pay_return_db->find($pid);

            //   $orders_db = D('orders');
            //   $data2['order_status'] = -1;
            //   $orders_db->where('order_sn="'.$payInfo['order_sn'].'"')->save($data2);
            // }
        }
        self::orders_pay_return_log($pay_return_log);

        return $pid;
    }

    /**
     * 退款记录之操作人记录
     * @param array $post
     */
    public static function orders_pay_return_log($post)
    {
        $data = array(
            'paytid' => $post['paytid'],
            'payt_status' => $post['payt_status'],
            'action_name' => $post['action_name'],
            'action_time' => $post['action_time'],
        );
        D('orders_pay_return_log')->add($data);
    }


    /**
     * 获取进货单商品列表
     * @param string $order_sn 订单号
     * @param int $isspec 是否核心供应商
     */
    public static function getPurchasedProductList($order_sn, $isspec = 1)
    {
        $order_db = D('orders');
        $orderInfo = $order_db->field('id,start_time,order_status,payment_status,shipping_status,confirm_time,order_sn,delivery_first_name,delivery_last_name,is_cheat')->where(array('order_sn' => $order_sn))->find();
        if (!$orderInfo) {
            return false;
        }
        $orderInfo['username'] = '';
        if ($orderInfo['user_id']) {
            $orderInfo['username'] = D('users')->where('id=' . $orderInfo['user_id'])->getField('username');
        }

        $where = array('order_id' => $orderInfo['id']);
        if ($isspec == 2) {
            $where['suppliers.isspec'] = 0;
        } elseif ($isspec == 3) {
            $where['suppliers.isspec'] = 1;
        }
        $order_item_db = D('orders_items');
        $order_item_db->field('orders_items.id AS orders_items_id,orders_items.product_sn,orders_items.product_name,orders_items.product_id,orders_items.attr,orders_items.qty,product.small_img,product.cost_price');
        $order_item_db->join('product ON product.id = orders_items.product_id');
        if ($isspec == 2 || $isspec == 3) {
            $order_item_db->join('suppliers ON suppliers.suppliers_id = product.suppliers_id');
        }
        $order_item_db->where($where);
        $productList = $order_item_db->select();
//  	echo $order_item_db->getLastSql();exit;
        if (!$productList) {
            unset($orderInfo);
        }

        if ($productList) {
            foreach ($productList as &$product) {
                if ($product['attr']) {
                    $data = unserialize($product['attr']);
                    if ($data) {
                        $attributes = array();
                        if ($product['custom_type']) {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $val['attr_name'] . ':' . $val['attr_value'];
                            }
                        } else {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $vk . ':' . $val;
                            }
                        }
                        $attribute = implode(' , ', $attributes);
                    }
                    $product['attr'] = $attribute;

                }
                $product['send_number'] = self::getDeliverySendNumber($product['orders_items_id']);
                $productInfo = ProductModel::getProductItems($product['product_id'], $language_id = C('language_id'));
                $product['summary'] = $productInfo[C('language_id')]['summary'];
            }
            unset($product);
            $orderInfo['productList'] = $productList;
        }

        return $orderInfo;
    }

    /**
     * 一个月内自动确认收货
     */
    public static function orderAutoConfirmedOneMonth()
    {
        $order_db = D('orders');
        $where = array(
            'order_status' => self::ORDER_CONFIRMED,
            'payment_status' => self::PAY_PAYED,
            'shipping_status' => array('IN', array(self::SHIPPING_SHIPPED, self::SHIPPING_SHIPPED_PART)),
            'orders_delivery.status' => 2,
        );

        $aftter_month_day = date('Y-m-d', strtotime("-1 month"));

        $where['orders_delivery.update_time'] = array(array('gt', strtotime($aftter_month_day)), array('lt', strtotime($aftter_month_day . ' 23:59:59')), 'AND');

        $order_db->field('orders.id');
        $order_db->join('orders_delivery ON orders.id=orders_delivery.order_id');
        $order_db->where($where)->order('orders_delivery.update_time DESC')->group('orders.id');
        $orderList = $order_db->select();
        if ($orderList) {
            foreach ($orderList as $order) {
                $data = array(
                    'order_status' => self::ORDER_COMPLETE,
                    'end_time' => time(),
                );
                $order_db->where('id = ' . $order['id'])->save($data);
                //根据发货量退款退积分
                OrderModel::returnedPartOrderPoints($order['id']);
            }
        }
//			echo $order_db->getLastSql();exit;
    }

    /**
     * 获取快递临时商品
     */
    public static function getOrderTempProductList()
    {
        $productList = array();
        $express_temp_product = D('express_temp_product');
        $productArr = $express_temp_product->select();
        if ($productArr) {
            foreach ($productArr as $arr) {
                $productList[$arr['id']] = $arr;
            }
        }
        return $productList;
    }

    /**
     * 获取所有欺诈信息列表
     */
    public static function getOrderCheatList()
    {
        if (!$cheatList = S('order_cheat_list')) {
            $order_cheat_db = D('orders_cheat');
            $cheatList = $order_cheat_db->select();
            S('order_cheat_list', $cheatList);
        }
        return $cheatList;
    }

    /**
     * 检测订单是否为欺诈订单
     * 四个值必须要三个相同才为欺诈
     * @param int $order_id 订单ID
     */
    public static function orderCheckCheat($order_id)
    {
        $fat = 0;//标识
        $orderInfo = self::getOrderInfo($order_id);
        $cheatList = self::getOrderCheatList();
        if (!($cheatList && $orderInfo) || $orderInfo['is_cheat']) {
            return false;
        }
        foreach ($cheatList as $cheat) {
            $fat = 0;
            if ($cheat['email'] == $orderInfo['delivery_email']) {
                $fat++;
            }
            if ($cheat['postalcode'] == $orderInfo['delivery_postcode']) {
                $fat++;
            }
            //前2项都不相同时不为欺诈
            if ($fat == 0) {
                continue;
            }

            if ($cheat['phone'] == $orderInfo['delivery_phone']) {
                $fat++;
            }

            //前3个都相同为欺诈
            if ($fat == 3) {
                break;
            }

            //前3项只有1个相同时不为欺诈
            if ($fat == 1) {
                continue;
            }

            if (stripos(str_replace(' ', '', $orderInfo['delivery_address']), str_replace(' ', '', $cheat['address'])) !== false) {
                $fat++;
            }
            if ($fat == 3) {
                break;
            }
        }
        $is_cheat = ($fat == 3) ? 2 : 1;
        $data = array('is_cheat' => $is_cheat);
        D('orders')->where('id=' . $order_id)->save($data);
    }

    /**
     * 获取分成金额
     * @param float $amount
     * @param int $qty
     */
    public static function getSharingFix($amount, $qty)
    {
        $user_sharing_type = C('user_sharing_type');
        $user_sharing_rate = C('user_sharing_rate');
        $user_sharing_fix = C('user_sharing_fix');
        if ($user_sharing_type == 1) {
            $price = floatval($amount) * $user_sharing_rate / 100;
        } else {
            $price = $user_sharing_fix * $qty;
        }
        if ($price) {
            return number_format($price, 2, '.', '');
        }
        return 0;
    }

    /**
     * 发放订单分成
     * @param int $order_id
     */
    public static function sendOrderSharing($order_id)
    {
        $orders_items_db = D('orders_items oi');
        $user_designer_product = D('user_designer_product');
        $orders_items_db->field('orders.order_sn,oi.id,oi.qty,oi.product_id,oi.product_name,oi.pay_price,oi.designer_id,oi.designer_product_id');
        $orders_items_db->join('orders ON orders.id = oi.order_id');
        $orders_items_db->where(array('oi.order_id' => $order_id, 'orders.order_status' => self::ORDER_COMPLETE, 'oi.designer_id' => array('gt', 0)));
//  	$orders_items_db->where(array('oi.order_id' => $order_id, 'orders.order_status' => self::ORDER_COMPLETE, 'oi.designer_id' => array('gt',0), 'oi.designer_product_id' => array('gt',0)));
        $itemsList = $orders_items_db->select();

        if ($itemsList) {
            $total_amount = 0;
            $data = array();
            foreach ($itemsList as $item) {
                $send_number = self::getDeliverySendNumber($item['id']);
                if ($send_number == 0) continue;

                //	$designer_name = $user_designer_product->where('designer_product_id='.$item['designer_product_id'])->getField('designer_name');
                $total_amount = number_format($send_number * $item['pay_price'], 2, '.', '');

                $sharing_price = self::getSharingFix($total_amount, $send_number);

                if ($sharing_price == 0) continue;
                $change_desc = L('_ORDER_SHARING_') . ' ' . L('order number : ') . $item['order_sn'] . ', ';
//	  		$change_desc .= $designer_name.' '.L('design according to your work into').' ';
                $change_desc .= $item['product_name'] . ' ' . L('sales of the product') . ', ';
                $change_desc .= L('qty') . ': ' . $send_number . ', ';
                $change_desc .= L('unit price') . ': ' . $item['pay_price'] . ', ';
                $change_desc .= L('total interface') . ': ' . $total_amount . ', ';
                $change_desc .= L('divided into') . ': ' . $sharing_price;

                $sharing_data = array(
                    'user_id' => $item['designer_id'],
                    'orders_items_id' => $item['id'],
                    'product_id' => $item['product_id'],
                    'order_id' => $order_id,
                    'order_sn' => $item['order_sn'],
                    'pay_price' => $item['pay_price'],
                    'pro_num' => $send_number,
                    'total_amount' => $total_amount,
                    'sharing_amount' => $sharing_price,
                );

                //发放分成
                if (self::insertOrderSharing($sharing_data)) {
                    UserModel::logAccountChange($item['designer_id'], $sharing_price, 0, 0, 0, $change_desc, UserModel::ACT_SHARING);
                }
            }

            //TODO分成邮件
        }

    }

    /**
     * 添加分成入表
     * @param array $post
     */
    public static function insertOrderSharing($post)
    {
        $data = array(
            'user_id' => $post['user_id'] ? $post['user_id'] : 0,
            'orders_items_id' => $post['orders_items_id'] ? $post['orders_items_id'] : 0,
            'product_id' => $post['product_id'] ? $post['product_id'] : 0,
            'order_id' => $post['order_id'] ? $post['order_id'] : 0,
            'order_sn' => $post['order_sn'] ? $post['order_sn'] : 0,
            'pay_price' => $post['pay_price'] ? $post['pay_price'] : 0,
            'pro_num' => $post['pro_num'] ? $post['pro_num'] : 0,
            'total_amount' => $post['total_amount'] ? $post['total_amount'] : 0,
            'sharing_amount' => $post['sharing_amount'] ? $post['sharing_amount'] : 0,
            'sharing_time' => time(),
        );
        $order_sharing = D('orders_sharing');
        $lastId = $order_sharing->add($data);
        return $lastId;
    }

    //更新国家列表
    public static function get_orderion_info($id)
    {
        $region_db = D('region');
        $regionInfo = $region_db->field('name,pid')->find($id);
        return $regionInfo;
    }

    /**
     *获取购物车中商品列表
     * @param boolean $is_collect 是否为收藏产品
     */
    public static function get_cart_product_list($is_collect = false, $attribute_type = 0, $user)
    {

        if (isset($user['id']) && $user['id']) {
            $where['user_id'] = $user['id'];
        } else {
            $where['user_id'] = 0;
            $where['sid'] = $user['sid'];
        }

        $where['is_collect'] = $is_collect ? 1 : 0;
        if ($attribute_type) {
            $where['car_type'] = 1;
        } else {
            $where['car_type'] = 0;
        }

        $cart_db = D('cart_products');
        $cartInfo = array(
            'total_weight' => 0,
            'total_amount' => 0,
            'total_number' => 0,
            'is_custom' => false,
        );

        $cartList = $cart_db->where($where)->order('add_time DESC')->select();

        if ($cartList) {
            foreach ($cartList as &$cart) {
                if ($cart['pid']) {

                    $attr = unserialize($cart['attr']);
                    $product = ProductModel::get_product_info($cart['pid'], 1);

                    if ($product['attribute_type'] == 1) {//正常价
                        $final_price = $product['custom_price'];
                    } elseif ($product['attribute_type'] == 2) {//定制价
                        $final_price = $product['advanced_price'];
                    }
                    $product['price'] = $final_price;

                    //**兼容原先数据
                    if ($attribute_type) {
                        $product['goods_amount'] = $product['sell_price'] * $cart['qty'];
                        $product['price'] = $product['sell_price'];
                    } else {
                        $product['goods_amount'] = $product['price'] * $cart['qty'];
                    }

                    //**兼容原先数据
                    if ($cart['price'] > 0 || $cart['pro_type'] > 0) { //兼容原先数据
                        //使用购物车里的价格
                        $product['price'] = $cart['price'];
                        $product['goods_amount'] = $cart['price'] * $cart['qty'];
                    }

                    $product['goods_weight'] = $product['weight'] * $cart['qty'];
                    $product['goods_dingjin'] = $product['yufu_price'] * $cart['qty'];

                    if ($cart['car_type'] == 0) {
                        $product['goods_dingjin'] = 0;
                    }
                    $cart['goods_amount'] = $product['goods_amount'];

                    //两件套 三件套 增加 附加裤子
                    if (in_array($product['model_id'], array(2, 18)) && $product['add_more'] == 1) {
                        $add_more_product = array();
                        $add_more_product['name'] = $product['name'] . ' - ' . 'Pants';
                        $add_more_product['price'] = $product['pants_price'];
                        $cart['add_pants'] = $add_more_product;
                        if ($cart['pants_qty'] > 0) {
                            $cartInfo['total_amount'] += $product['pants_price'] * $cart['pants_qty'];
                        }
                    } else {
                        if ($cart['pants_qty'] > 0) {
                            D('cart_products')->where(array('id' => $cart['id']))->save(array('pants_qty' => 0));
                            $cart['pants_qty'] = 0;
                        }
                    }

                    $cart['product'] = $product;
                    $cartInfo['total_weight'] += $product['goods_weight'];
                    $cartInfo['total_amount'] += $product['goods_amount'];
                    $cartInfo['total_dingjin'] += $product['goods_dingjin'];
                    if (!$cart['car_type']) $cartInfo['total_number'] += $cart['qty'];
                }
            }
            unset($cart);

            $cartInfo['productList'] = $cartList;
        }

        return $cartInfo;
    }

    /**
     * 获取保存身型数据的id
     * @param int $measure_id 身型id
     * @param int $order_item_id order_item表的id
     * @return boolean
     */
    public static function isset_size_measure($measure_id, $order_item_id)
    {

        $size_measure = D('size_measure');
        $where = array(
            'measure_id' => $measure_id,
            'order_item_id' => $order_item_id,
        );
        $res = $size_measure->where($where)->getField('id');

        return (boolean)$res;


    }

    /**
     * 设置保存修改身型数据
     * @param int $measure_id 身型id
     * @param int $order_item_id order_item表的id
     * @param varche $data 序列化的数据
     * @return boolean
     */
    public static function set_size_measure($measure_id, $order_item_id, $data)
    {

        $data = serialize($data);
        $addData = array(
            'measure_id' => $measure_id,
            'order_item_id' => $order_item_id,
        );

        $size_measure = D('size_measure');
        $res = self::isset_size_measure($measure_id, $order_item_id);
        if ($res) {
            $res = $size_measure->where($addData)->save(array('data' => $data, 'time' => time()));
            return (boolean)$res;
        }

        $addData['data'] = $data;
        $addData['time'] = time();
        $res = $size_measure->add($addData);
        return (boolean)$res;
    }

    /**
     * 判断是否全设置的身型数据
     * @param int $order_id 订单id
     * @return boolean
     */
    public static function isset_size($order_id)
    {

        $orders_items_db = D('orders_items');
        $where = array(
            'order_id' => $order_id,
            'custom_type' => 2,
        );
        $orders_items = $orders_items_db->field('id')->where($where)->select();

        foreach ($orders_items as $val) {
            $res = self::isset_size_measure(0, $val['id']);
            if (!$res) return (boolean)$res;
        }
        return (boolean)$res;

    }

    /**
     * 获取每种类型的字体，颜色，类型的key
     * @param int $order_item_id 子订单id
     * @return array
     */
    public static function font_key($orderfigure, $model_id)
    {
        $default_val = 99999;
        $font_1_key = $font_2_key = $font_zt_key = $font_color_key = $default_val;
        if ($model_id == 2) { // suit
            $font_1_key = 30;
            $font_2_key = 31;
            $font_zt_key = 32;
            $font_color_key = 33;
        } elseif ($model_id == 18) { //three suit
            $font_1_key = 99;
            $font_2_key = 100;
            $font_zt_key = 101;
            $font_color_key = 102;
        } elseif ($model_id == 14) { //shirt
            $font_1_key = 80;
            $font_zt_key = 81;
            $font_color_key = 82;
        } elseif ($model_id == 20) { //vest
        } elseif ($model_id == 21) { //pants
        } elseif ($model_id == 1) { //jacket
            $font_1_key = isset($orderfigure['attr_array']['64']) ? 64 : 30;
            $font_2_key = isset($orderfigure['attr_array']['65']) ? 65 : 31;
            $font_zt_key = 66;
            $font_color_key = isset($orderfigure['attr_array']['67']) ? 67 : 33;
        } elseif ($model_id == 22) {//coat
            $font_1_key = 143;
            $font_2_key = 144;
            $font_zt_key = 145;
            $font_color_key = 146;
        } elseif ($model_id == 23) { //特殊礼服处理
            $font_1_key = isset($orderfigure['attr_array']['139']) ? 139 : 30;
            $font_2_key = isset($orderfigure['attr_array']['140']) ? 140 : 31;
            $font_zt_key = 141;
            $font_color_key = 142;
        } elseif ($model_id == 25) { //鞋子的绣字
            $font_1_key = 155;
        }
        return array($font_1_key, $font_2_key, $font_zt_key, $font_color_key);
    }

}